﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Dare.Utilities.Data;
using Stone.Data.Providers;

namespace Stone.Services
{
    public class DatabaseService : DbServiceBase
    {
        DatabaseDataProvider provider;
        public DatabaseService(Application app)
            : base(app)
        {
            provider = app.DataProviderManagerFactory.Default.GetDataProvider<DatabaseDataProvider>();
        }

        public DataTable Select2Table(string sql)
        {
            DataTable dt = null;

            if (Execute(delegate(TransactionManager manager)
            {
                dt = provider.SelectAsTable(manager, sql);
            }))
            {
                return dt;
            }
            else
            {
                return null;
            }
        }

        public T Execute<T>(string sql,T t)
        {
            T obj = default(T);
            if (Execute(delegate(TransactionManager manager)
            {
                obj = provider.ExecuteScalar<T>(manager, sql, t);
            }))
            {
                return obj;
            }
            else
            {
                return t;
            }
        }

        public int Execute(string sql)
        {
            int nRet = 0;
            if (Execute(delegate(TransactionManager manager)
            {
                nRet = provider.ExecuteNonQuery(manager, sql);
            }))
            {
                return nRet;
            }
            else
            {
                return -1;
            }
        }

        //获取数据库时间
        public DateTime? GetDataTime()
        {
            DateTime? dateTime = null;
            if (Execute(delegate(TransactionManager manager)
            {
                dateTime = provider.GetDateTime(manager);
            }))
            {
                return dateTime;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <returns></returns>
        public bool InitDatabase()
        {
            return Execute(delegate(TransactionManager manager)
            {
                provider.InitDatabase(manager);
            });
        }
    }
}
